//
//  SJHiddenNavigationC.swift
//  SJNavigationBarDemo
//
//  Created by swordjoy on 2017/4/29.
//  Copyright © 2017年 swordjoy. All rights reserved.
//

import UIKit

class SJHiddenNavigationC: UINavigationController {

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return topViewController?.preferredStatusBarStyle ?? .default
    }
    
    override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
        return .fade
    }
    
  override func viewDidLoad() {
    super.viewDidLoad()

    interactivePopGestureRecognizer?.delegate = self
    delegate = self
    
  }
  
  override func pushViewController(_ viewController: UIViewController, animated: Bool) {
    
    if viewControllers.count > 0 {
      viewController.hidesBottomBarWhenPushed = true
    }
    if animated { interactivePopGestureRecognizer?.isEnabled = false }
    
    super.pushViewController(viewController, animated: true)
    
  }
  
  override func popToRootViewController(animated: Bool) -> [UIViewController]? {
    
    if animated { interactivePopGestureRecognizer?.isEnabled = false }
    
    return super.popToRootViewController(animated: animated)
    
  }
  
  override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
    
    if animated { interactivePopGestureRecognizer?.isEnabled = false }
    
    return super.popToViewController(viewController, animated: animated)
    
  }
  
}

extension SJHiddenNavigationC: UIGestureRecognizerDelegate {

  func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    
    if gestureRecognizer == interactivePopGestureRecognizer && viewControllers.count < 2 {
      return false
    }
    
    return true
    
  }
  
}

extension SJHiddenNavigationC: UINavigationControllerDelegate {

  func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    
    interactivePopGestureRecognizer?.isEnabled = true
    
  }
  
}
